package com.wechet.controller;

import com.sun.org.apache.xpath.internal.operations.Mod;
import com.wechet.common.CookieUtil;
import com.wechet.common.RedisConst;
import com.wechet.config.ProjectUrl;
import com.wechet.domain.SellerInfo;
import com.wechet.exception.SellException;
import com.wechet.serveice.impl.SellerServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * Created by sc on 2017/9/29.
 */
@Controller
@RequestMapping("/seller")
public class SellerUserController {

    @Autowired
    private SellerServiceImpl sellerService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private ProjectUrl projectUrl;


    @GetMapping("/login")
    public ModelAndView login(@RequestParam("openid") String openid, HttpServletResponse response, Map<String, Object> map) {
        //1.匹配数据库openid
        //2.设置token到redis
        //3.设置token到token
        SellerInfo sellerInfo = new SellerInfo();
        try {
            sellerInfo = sellerService.findSellerInfoByOpenId(openid);
        } catch (SellException e) {
            map.put("msg", e.getMessage());
            map.put("url", "/sell/seller/login");
            return new ModelAndView("common/error", map);
        }
        String token = UUID.randomUUID().toString();
        Integer expire = RedisConst.EXPIRE;
        stringRedisTemplate.opsForValue().set(String.format(RedisConst.TOKEN_PREFIX, token), openid, expire, TimeUnit.SECONDS);
        CookieUtil.set(response, "token", token, expire);
        String url = "/seller/order/list";
        return new ModelAndView("redirect:" + url);
    }

    @GetMapping("/logout")
    public ModelAndView logout(HttpServletRequest request, HttpServletResponse response, Map<String, Object> map) {

        //1.从cookie查
        Cookie cookie = CookieUtil.get(request, "token");
        if (cookie != null) {
            //2.清除redis
            //3.清除cookie
            stringRedisTemplate.opsForValue().getOperations().delete(String.format(RedisConst.TOKEN_PREFIX, cookie.getValue()));
            CookieUtil.set(response, "token", null, 0);
        }
        map.put("msg", "登出成功");
        map.put("url", "/index/index");
        return new ModelAndView("common/success", map);
    }
}
